<template>
  <div class="main">
    <el-dialog
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      title="添加分配"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="addAssignment"
    >
      <div class="tip" v-if="openTip">
        <svg-icon class="circleTip" icon-class="circle-tip"></svg-icon>
        <div class="content">
          设备最多只能存在一个已激活的分配，如需新增请先释放当前已有
          <span
            class="to_release"
            @click="to_release"
            v-permission="[10, 'icon']"
            >去释放</span
          >
        </div>
      </div>

      <el-tabs
        class="tabHight"
        v-model="activeName"
        :tab-position="tabPosition"
        @tab-click="tabChange"
      >
        <div v-if="activeName != 'tab_4'">
          <div style="float: left; margin: 7px 0 15px 0; color: #333333">
            分配目标：
            <span style="color: #666666">{{ addAssignmentDeviceName }}</span>
          </div>
          <div style="float: right">
            <el-input
              v-model="searchData"
              size="mini"
              placeholder="请输入名称"
              clearable
              style="width: 218px; margin-right: 4px"
              @clear="clear"
            />
            <el-button size="mini" type="primary" @click="search()"
              ><i class="el-icon-search"></i>搜索</el-button
            >
          </div>
        </div>
        <el-tab-pane label="用户" name="tab_1">
          <el-table
            class="table"
            height="270"
            :data="customerSearchList"
            :header-cell-style="{ background: '#FAFAFA' }"
            ref="multipleTableCustomer"
            @selection-change="handleSelectionChangeCustomer"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="longitude" label="图片" width="85">
              <template slot-scope="scope">
                <img
                  :src="scope.row.url | filtersFileUrl()"
                  style="width: 35px; height: 35px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="username" label="名称" width="200">
            </el-table-column>
            <el-table-column prop="remark" label="描述"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="站点" name="tab_2">
          <el-table
            class="table"
            height="270"
            :data="areasSearchList"
            :header-cell-style="{ background: '#FAFAFA' }"
            ref="multipleTableArea"
            @selection-change="handleSelectionChangeArea"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="longitude" label="图片" width="85">
              <template slot-scope="scope">
                <img
                  :src="scope.row.imageUrl | filtersFileUrl()"
                  style="width: 35px; height: 35px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" width="200">
            </el-table-column>
            <el-table-column prop="description" label="描述"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="网关" name="tab_3">
          <el-table
            class="table"
            height="270"
            :data="assetsSearchList"
            :header-cell-style="{ background: '#FAFAFA' }"
            ref="multipleTableAsset"
            @selection-change="handleSelectionChangeAsset"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              prop="longitude"
              label="图片"
              width="284"
              align="center"
            >
              <template slot-scope="scope">
                <img
                  :src="scope.row.imageUrl | filtersFileUrl()"
                  style="width: 35px; height: 35px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="音箱" name="tab_5">
          <el-table
            class="table"
            height="270"
            :data="boxSearchList"
            :header-cell-style="{ background: '#FAFAFA' }"
            ref="multipleTableBox"
            @selection-change="handleSelectionChangeBox"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="longitude" label="图片" align="center">
              <template slot-scope="scope">
                <img
                  :src="scope.row.imageUrl | filtersFileUrl()"
                  style="width: 35px; height: 35px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称"> </el-table-column>
            <el-table-column prop="model" label="模式"> </el-table-column>
            <el-table-column prop="brand" label="品牌"> </el-table-column>
            <el-table-column prop="ip" label="IP"> </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="元数据" name="tab_4">
          <metaData
            :editmetaData="editmetaData"
            @sendmetaDatas="sendmetaData"
          />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-permission="[9, 'button']"
          size="mini"
          type="primary"
          @click="submitForm()"
          :disabled="isDisabled"
          :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MetaData from "../../opensite/metaData.vue";
import { gatewayInfo } from "@/api/gateway";
import { getUserList } from "@/api/userAuth";
import { createAssignments } from "@/api/device";
import { getAssignmentSearchList } from "@/api/assignments";
import { getDistributionAreas } from "@/api/superlinkAreat";
import { getAssetsList } from "@/api/assets";
import { releaseAssignments } from "@/api/assignments";

import { getList } from "@/api/loudspeakerBox";
export default {
  props: {
    addAssignment: {
      type: Boolean,
      default: false
    },
    addAssignmentDeviceToken: {
      type: String,
      default: ""
    },
    addAssignmentDeviceName: {
      type: String,
      default: ""
    }
  },
  components: {
    MetaData
  },
  data() {
    return {
      boxSearchList: [],
      boxList: [],
      loading: false,
      tabPosition: "left",
      activeName: "tab_1",
      openTip: false,
      isDisabled: false,
      activeAssignmentId: "",
      activeAssignmentToken: "",
      editmetaData: [],
      metaDataJson: {},
      customerList: [],
      areasList: [],
      assetsList: [],
      customerSearchList: [],
      areasSearchList: [],
      assetsSearchList: [],
      multipleSelectionsCustomer: "",
      multipleSelectionsArea: "",
      multipleSelectionsAsset: "",
      searchData: "",
      customerSearch: "",
      areaSearch: "",
      boxSearch: "",
      assetSearch: "",
      username: "",
      searchFirst: {},
      multipleSelectionsBox: []
    };
  },
  mounted() {
    // this.gatewayInfo("9d5c78ba-748b-409f-b636-da88cd59b295");
  },
  watch: {},
  methods: {
    getAssignmentList() {
      return new Promise((reslove, reject) => {
        var that = this;
        var params = {
          deviceTokens: [that.addAssignmentDeviceToken],
          assignmentStatuses: ["Active"]
        };
        getAssignmentSearchList(
          params,
          "includeArea=true&includeAsset=true&includeCustomer=false&includeDevice=true&page=1&pageSize=20&userIds="
        ).then(res => {
          const r = res.data;
          console.log(r.results, "r.results");
          if (r.results.length) {
            this.openTip = true;
            this.isDisabled = true;
            this.activeAssignmentId = r.results[0].ideviceAssignment.id;
            this.activeAssignmentToken = r.results[0].ideviceAssignment.token;
            this.searchFirst = {
              userId: r.results[0].user.userId,
              areaId: r.results[0].ideviceAssignment.area.token,
              assetId: r.results[0].ideviceAssignment.asset.token,
              voiceBoxId: r.results[0].ideviceAssignment.voiceBoxId
            };
          } else {
            this.openTip = false;
            this.isDisabled = false;
            this.searchFirst = {};
          }
          reslove();
        });
      });
    },
    //搜索
    search() {
      if (this.activeName == "tab_1") {
        // this.getCustomersList();
        this.customerSearch = this.searchData;
        this.customerSearchList = this.filter(
          this.customerSearch,
          this.customerList,
          "username"
        );
      } else if (this.activeName == "tab_2") {
        this.areaSearch = this.searchData;
        this.areasSearchList = this.filter(this.areaSearch, this.areasList);
      } else if (this.activeName == "tab_3") {
        this.assetSearch = this.searchData;
        this.assetsSearchList = this.filter(this.assetSearch, this.assetsList);
      } else if (this.activeName == "tab_5") {
        this.boxSearch = this.searchData;
        this.boxSearchList = this.filter(this.boxSearch, this.boxList);
      }
    },
    clear() {
      this.search();
    },
    //tab切换
    tabChange() {
      if (this.activeName == "tab_1") {
        this.searchData = this.customerSearch;
      } else if (this.activeName == "tab_2") {
        this.searchData = this.areaSearch;
      } else if (this.activeName == "tab_3") {
        this.searchData = this.assetSearch;
      } else if (this.activeName == "tab_5") {
        this.searchData = this.assetSearch;
      }
    },
    //搜索过滤
    filter(filterData, listData, key = "name") {
      return listData.filter(
        data =>
          !filterData ||
          data[key].toLowerCase().includes(filterData.toLowerCase())
      );
    },
    //多选变单选处理
    handleSelectionChangeCustomer(val) {
      if (val.length > 1) {
        this.$refs.multipleTableCustomer.clearSelection(); //清除

        this.$refs.multipleTableCustomer.toggleRowSelection(val.pop()); //poplog(：最后一个
      } else {
        this.multipleSelectionsCustomer = val[0];
      }
    },
    handleSelectionChangeArea(val) {
      if (val.length > 1) {
        this.$refs.multipleTableArea.clearSelection(); //清除
        this.$refs.multipleTableArea.toggleRowSelection(val.pop()); //poplog(：最后一个
      } else {
        this.multipleSelectionsArea = val[0];
      }
    },
    handleSelectionChangeAsset(val) {
      if (val.length > 1) {
        this.$refs.multipleTableAsset.clearSelection(); //清除
        this.$refs.multipleTableAsset.toggleRowSelection(val.pop()); //poplog(：最后一个
      } else {
        this.multipleSelectionsAsset = val[0];
      }
    },
    handleSelectionChangeBox(val) {
      if (val.length > 1) {
        this.$refs.multipleTableBox.clearSelection(); //清除
        this.$refs.multipleTableBox.toggleRowSelection(val.pop()); //poplog(：最后一个
      } else {
        this.multipleSelectionsBox = val[0];
      }
    },
    //弹窗打开执行操作
    async handleOpen() {
      console.log("1 :>> ", 2);
      this.activeName = "tab_1";
      await this.getAssignmentList();
      this.getCustomersList();
      this.getAreasList();
      this.getAssetsLists();
      this.getboxs();
    },
    // 获取音箱
    getboxs() {
      getList({
        page: 1,
        pageSize: 0
      }).then(res => {
        this.boxSearchList = res.data.results;
        this.boxList = res.data.results;
        this.$nextTick(() => {
          this.boxSearchList.forEach(item => {
            if (item.id == this.searchFirst.voiceBoxId) {
              this.$refs.multipleTableBox.toggleRowSelection(item, true);
            }
          });
        });
      });
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      this.$emit("changeShow", isRefresh);
      this.cancelEmpty();
    },
    //取消清空数据
    cancelEmpty() {
      this.editmetaData = [];
      this.metaDataJson = {};
    },
    //获取用户列表
    getCustomersList() {
      getUserList(this.searchData).then(res => {
        this.customerSearchList = res.data.data;
        this.customerList = res.data.data;
        this.$nextTick(() => {
          this.customerSearchList.forEach(item => {
            if (item.id == this.searchFirst.userId) {
              this.$refs.multipleTableCustomer.toggleRowSelection(item, true);
            }
          });
        });
      });
    },
    //获取站点列表
    getAreasList() {
      var params = {
        includeAreaType: false,
        includeAssignments: false,
        includeZones: false,
        rootOnly: false,
        page: 1,
        pageSize: 0
      };
      getDistributionAreas(params).then(res => {
        const r = res.data;
        this.areasList = r.results;
        this.areasSearchList = r.results;
        this.$nextTick(() => {
          this.areasList.forEach(item => {
            if (item.token == this.searchFirst.areaId) {
              this.$refs.multipleTableArea.toggleRowSelection(item, true);
            }
          });
        });
      });
    },
    //获取网关列表
    getAssetsLists() {
      var params = { includeAssetType: false, page: 1, pageSize: 0 };
      getAssetsList(params).then(res => {
        const r = res.data;
        this.assetsList = r.results;
        this.assetsSearchList = r.results;
        this.$nextTick(() => {
          this.assetsList.forEach(item => {
            if (item.token == this.searchFirst.assetId) {
              this.$refs.multipleTableAsset.toggleRowSelection(item, true);
            }
          });
        });
      });
    },

    // 提交
    submitForm() {
      let formData = {
        deviceToken: this.addAssignmentDeviceToken,
        userId: null,
        areaToken: null,
        assetToken: null,
        metadata: {},
        voiceBoxToken: ""
      };
      formData.metadata = this.metaDataJson;
      // 用户

      if (this.multipleSelectionsCustomer) {
        formData.userId = this.multipleSelectionsCustomer.id;
      } else {
        this.$msg("添加分配必须选择用户！");
        return false;
      }
      if (this.multipleSelectionsArea) {
        formData.areaToken = this.multipleSelectionsArea.token;
      } else {
        this.$msg("添加分配必须选择站点！");
        return false;
      }
      if (this.multipleSelectionsAsset) {
        formData.assetToken = this.multipleSelectionsAsset.token;
      } else {
        this.$msg("添加分配必须选择网关！");
        return false;
      }
      if (this.multipleSelectionsBox) {
        formData.voiceBoxToken = this.multipleSelectionsBox.token;
      } else {
        this.$msg("添加分配必须选择音箱！");
        return false;
      }
      this.loading = true;
      createAssignments(formData, formData.userId)
        .then(res => {
          this.$msg({
            type: "success",
            message: "操作成功!"
          });
          // 添加成功走一个后台接口
          // this.gatewayInfo(res.data.id);
          this.handleClose(true);
        })
        .finally(f => {
          this.loading = false;
        });
    },
    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },
    gatewayInfo(assignmentsId) {
      gatewayInfo({
        tenantToken: this.$store.getters.tenant.token,
        assignmentsId
      }).then(res => {
        console.log(res, "gatewayInfogatewayInfo");
      });
    },

    //去释放
    to_release() {
      this.$confirm("即将释放分配 : " + this.activeAssignmentId, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        releaseAssignments(this.activeAssignmentToken, "/end").then(res => {
          this.$msg({
            type: "success",
            message: "操作成功!"
          });
          this.$nextTick(() => {
            this.$refs.multipleTableCustomer.clearSelection();
            this.$refs.multipleTableArea.clearSelection();
            this.$refs.multipleTableAsset.clearSelection();
            this.isDisabled = false;
          });
          this.getAssignmentList();
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table {
  width: 100%;
}
/deep/ thead .el-table-column--selection .cell {
  display: none !important;
}
/deep/ .el-message-box {
  width: 410px;
}
.tip {
  height: 40px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 2px;
  margin: 0 0 15px 33px;
  width: 95.5%;
  .content {
    padding: 0 14px;
    font-size: 14px;
    line-height: 22px;
    margin: -19px 0 0 18px;
    .to_release {
      float: right;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 22px;
      color: #ff9900;
      text-decoration: underline;
      cursor: pointer;
    }
  }
  .circleTip {
    width: 16px;
    height: 16px;
    margin: 10px 0px 0 13px;
  }
}
</style>
